// import JSEncrypt from 'jsencrypt/bin/jsencrypt'
import JSEncrypt from "node-jsencrypt";
import CryptoJS from 'crypto-js';
import crypto from "crypto";

// 密钥对生成 http://web.chacuo.net/netrsakeypair

const publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdH\n' +
  'nzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ=='

const privateKey = 'MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqhHyZfSsYourNxaY\n' +
  '7Nt+PrgrxkiA50efORdI5U5lsW79MmFnusUA355oaSXcLhu5xxB38SMSyP2KvuKN\n' +
  'PuH3owIDAQABAkAfoiLyL+Z4lf4Myxk6xUDgLaWGximj20CUf+5BKKnlrK+Ed8gA\n' +
  'kM0HqoTt2UZwA5E2MzS4EI2gjfQhz5X28uqxAiEA3wNFxfrCZlSZHb0gn2zDpWow\n' +
  'cSxQAgiCstxGUoOqlW8CIQDDOerGKH5OmCJ4Z21v+F25WaHYPxCFMvwxpcw99Ecv\n' +
  'DQIgIdhDTIqD2jfYjPTY8Jj3EDGPbH2HHuffvflECt3Ek60CIQCFRlCkHpi7hthh\n' +
  'YhovyloRYsM+IS9h/0BzlEAuO0ktMQIgSPT3aFAgJYwKpqRYKlLDVcflZFCKY7u3\n' +
  'UP8iWi1Qw0Y='

// 加密
export function encrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey) // 设置公钥
  return encryptor.encrypt(txt) // 对数据进行加密
}

// 解密
export function decrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPrivateKey(privateKey) // 设置私钥
  return encryptor.decrypt(txt) // 对数据进行解密
}

const pubKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkuw2eiBRakI0vXfcr8HI65PLp6yoJNmFJk7f0rc8Uppa9DONRRkjdPW4uWeiWrl+sUP/n2WyKSUjIL9Wgg1vcLkFRBdX0sHfX+8gue+gDgCliojVREvwq7K92oFzCGTlCfYF+ftPtMprtcm0ipEyX2IJUwFcVVyyvXNoJhdHNgtNMSUnCCV0uwxRtkKlsDALAbsB2IGvkmsrWvNFGXb4VDxA/g765AAuENbChl7HwmMjGUmbNK/WgFSbfH2PMwMw8mhdLJksIyLCmYgRWc8scvG0XIXYCG+ZnKNRR8i6IWPlPQqEOJWW9uCStmJMnhOmeBqNzwFpHsjLJ7Z4JHER7QIDAQAB'
const prefixPubkey = '-----BEGIN PUBLIC KEY-----\n'
const suffixPubkey = '\n-----END PUBLIC KEY-----'

export function encryptRsaPublic(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(pubKey) // 设置公钥
  return encryptor.encrypt(txt) // 对数据进行加密
}

// JSEncrypt这个工具，不能用公钥解密
export function decryptRsaPublicErr(encryptedBase64) {
  const decryptor = new JSEncrypt()
  decryptor.set(pubKey)
  const decrypted = decryptor.decrypt(encryptedBase64)
  return decrypted
}

export function decryptRsaPublic(encryptedBase64) {
  const encryptedBuffer = Buffer.from(encryptedBase64, 'base64');
  let decrypted;
  try {
    decrypted = crypto.publicDecrypt(
      {
        key: prefixPubkey + pubKey + suffixPubkey,
        padding: crypto.constants.RSA_PKCS1_PADDING
      },
      encryptedBuffer
    );
    return decrypted.toString('utf8');
  } catch (pkcs1Error) {
    console.log('❌ PKCS1 填充失败:', pkcs1Error.message);
  }

}

/**
 * 随机生成16位的AES密钥
 * @returns {string}
 */
export const getAESKey = () => {
  var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
    'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
    'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  var n = 16;
  var res = "";
  for (var i = 0; i < n; i++) {
    var id = Math.ceil(Math.random() * 35);
    res += chars[id];
  }
  return res;
}

/**
 * 加密
 * @param data
 * @param aesKey
 * @returns {string}
 * @constructor
 */
export const WithAes = (data, aesKey) => {
  let key = CryptoJS.enc.Utf8.parse(aesKey);
  let srcs = CryptoJS.enc.Utf8.parse(data);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.ciphertext.toString();
};

/**
 * 解密Aes
 * @param data
 * @param aesKey
 * @returns {string}
 */
export const decryptAes = (data, aesKey) => {
  let keyStr;
  keyStr = aesKey ? aesKey : "1234567890abcdef";
  var key = CryptoJS.enc.Utf8.parse(keyStr);
  var decrypt = CryptoJS.AES.decrypt(CryptoJS.format.Hex.parse(data), key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
};

function example() {
  const mingWen = "hello world"
  const miWen = encryptRsaPublic(mingWen)
  console.log("公钥加密后=：" + miWen);
}

example()
